<template>
	<div class="contract_main">
		<el-row class="head">
			<el-col :span="24">
				<h1 class="contract_title">订单合同</h1>
				<span>/ 管理客户合同和条款</span>
			</el-col>
		</el-row>
		<div class="nav">
			<div class="nav-item">
				<el-button type="text" @click="openSave">
					<i class="iconfont icon-qianbi"></i>新增
				</el-button>
			</div>
			<div class="nav-item">
				<!-- 导出 -->
				<download-excel :data="allContract" :fields="excelFields" name="合同列表.xls" type="xls">
					<el-button type="text">
						<i class="iconfont icon-excel">导出Excel</i>
					</el-button>
				</download-excel>
			</div>
			<el-form style="display:inline-block">
				<div style="display: inline-block;height: 45px;padding: 0px 15px;width:150px">
					<el-select v-model="searchBy" style="width:100% !important" @change="search = ''">
						<el-option v-for="item in searchBys" :key="item" :value="item"></el-option>
					</el-select>
				</div>
				<div class="nav-item" style="border:none;">
					<el-input v-model="search" v-if="searchBy === '合同编号' || searchBy === '客户名称'" clearable></el-input>
					<el-date-picker value-format="yyyy-MM-dd" style="width:180px" v-model="search" v-if="searchBy === '签约时间'"></el-date-picker>
				</div>
				<div style="display:inline-block">
					<el-button @click="get_conState()">搜索</el-button>
				</div>
			</el-form>
		</div>
		<div class="content" v-loading="loading">
			<!-- tabs导航 -->
			<el-tabs v-model="activeNameTable" type="border-card" @tab-click="chang_tab">
				<el-tab-pane label="全部" name="first" state="0">
					<contract-table ref="refContractTable" :contracts="contracts" :constates="conStates"></contract-table>
				</el-tab-pane>
				<el-tab-pane v-for="item in conStates" :key="item.id" :label="item.name" :name="item.id+''" :state="item.id">
					<contract-table ref="refContractTable" :contracts="contracts" :constates="conStates"></contract-table>
				</el-tab-pane>
				<!-- 分页 -->
				<div class="block" style="margin-top:10px">
					<el-pagination background layout="total, prev, pager, next" 
					:total="total" 
					:current-page.sync="curr_page" 
					:page-size="page_size" 
					@current-change="changge_page"></el-pagination>
				</div>
			</el-tabs>
		</div>
		<!-- 合同抽屉中的更过操作 -->
		<el-drawer :with-header="false" :visible.sync="drawer" destroy-on-close modal-append-to-body>
			<contract-drawer ref="contractDrawer" :contract="contract"></contract-drawer>
		</el-drawer>
		
		<!-- 新增和修改合同的弹窗 -->
		<el-dialog title="合同" :visible.sync="savaContractDialogVisible" width="60%" top="5vh" destroy-on-close>
			<save-contract ref="refSaveContract"></save-contract>
		</el-dialog>
		<!-- 回款计划弹窗 -->
        <el-dialog title="回款计划" :visible.sync="backToArticlePlanDialogVisible" width="60%" destroy-on-close>
            <back-article-plan ref="refBackToArticlePlan" :contract="contract"></back-article-plan>
        </el-dialog>
		<!-- 回款记录弹窗 -->
        <el-dialog title="回款记录" :visible.sync="backToArticleRecordDialogVisible" width="60%" destroy-on-close>
            <back-article-record ref="refBackToArticleRecord" :contract="contract"></back-article-record>
        </el-dialog>
		<!-- 交付计划弹窗 -->
        <el-dialog title="交付计划" :visible.sync="deliveryPlanDialogVisible" width="60%" destroy-on-close>
            <delivery-plan ref="refDeliveryPlan" :contract="contract"></delivery-plan>
        </el-dialog>
		<!-- 交付记录弹窗 -->
        <el-dialog title="交付记录" :visible.sync="deliveryRecordDialogVisible" width="60%" destroy-on-close>
            <delivery-record ref="refDeliveryRecord" :contract="contract"></delivery-record>
        </el-dialog>
		<!-- 开票记录弹窗 -->
        <el-dialog title="开票记录" :visible.sync="conInvoiceRecordDialogVisible" width="60%" destroy-on-close>
            <con-invoice-record ref="refConInvoiceRecord" :contract="contract"></con-invoice-record>
        </el-dialog>
	</div>
</template>

<script>
import {formatTimeToStr} from "../../assets/format"
export default {
	name: "contract",
	components: {
		'contract-table': resolve => require(["./contract_table"],resolve),				// 合同列表组件标签
		'save-contract': resolve => require(["./save_contract"],resolve),				// 新增和修改组件标签
		'back-article-plan': resolve => require(["./back_to_article_plan"],resolve), 	// 回款计划
		'back-article-record': resolve => require(["./back_to_article_record"],resolve),// 回款记录
		'delivery-plan': resolve => require(["./delivery_plan"],resolve),				// 交付计划
		'delivery-record': resolve => require(["./delivery_record"],resolve),			// 交付记录
		'contract-drawer': resolve => require(["./contract_drawer"],resolve),			// 抽屉组件内容
		'con-invoice-record':resolve => require(["./con_invoice_record"], resolve) // 开票记录
	},
	data: function () {
		return {
			user:{},
			loading:true,
			activeNameTable: "first",	// tabs导航标识
			conStates:[],				// 合同状态列表，用于tabs导航的遍历
			contracts:[],				// 合同的数据源
			state:0,					// 合同状态标识
			
			drawer: false,				//合同详情抽屉控制开关
			contract: {},				//合同对象，用于在抽屉中修改
			search:'',					// 搜索关键词
			searchBy:'合同编号',		 // 搜索条件
			searchBys:[					// 条件选项
				'合同编号','客户名称','签约时间'
			],				
			// 产品列表
			productList: [],
			
			deliveryRecordDialogVisible: false,	// 交付记录弹窗开关
			deliveryPlanDialogVisible: false,	// 交付计划弹窗开关
			savaContractDialogVisible: false,  //合同新增和修改的弹窗控制开关
			backToArticlePlanDialogVisible: false,	// 回款计划弹窗开关
			backToArticleRecordDialogVisible: false,	// 回款记录弹窗开关
			conInvoiceRecordDialogVisible:false,		// 合同开票记录开关
			// 分页参数
			page_size:6,
			total:0,
			curr_page:1,
			// excel导入
			fileTemp:null,
            file:null,
            da:[],
			dalen:0,
			tempContracts:[],		// 临时合同集合
			// 导出excel
			allContract:[],			// 全部的合同数据（非分页数据），用于导出excel
			excelFields:{			// excel对应关系
				"合同名称":"contractNum",
				"客户":"customer.customerName",		// 支持嵌套属性
				"合同状态":"conState.name",
				"分类":"classify.name",
				"回款金额":"returnMoney",
				"总金额":"totalMoney",
				"开始时间":{
					field:"startTime",
					callback: value => {		// 通过回调函数格式化日期
						return formatTimeToStr(value[0],"yyyy-MM-dd")
					}
				},
				"结束时间":{
					field:"startTime",
					callback: value => {
						return formatTimeToStr(value[1],"yyyy-MM-dd")
					}
				},
				"客户签约人":"customerSigner",		// 常规字段
				"我方签约人":"empSigner.empName",
				"签约时间":{
					field:"signTime",
					callback: value => {
						return formatTimeToStr(value,"yyyy-MM-dd")
					}
				},
				"合同产品":{
					field:"productList",
					callback: value => {
						let product = ""
						value.forEach(pl => {
							let p =	pl.proDetail.product.productName
							pl.proDetail.abilities.forEach(ab => {
								p += " " + ab.abilityName
							})
							product += p + " | "
						})
						return product.substring(0, product.length-1)
					}
				},
				"附件下载地址":"conFilesUrl"
			}
		};
	},
	methods: {
		/* 获取合同状态列表 */
		get_conState(){
			this.axios.get("api/dd/conStates")
			.then(res => {
				this.conStates = res.data
				this.get_contracts(this.curr_page, 0)
			})
			.catch(() => {
				this.loading = false
				this.global.mes_error("获取数据失败！")
			})
		},

		/* 获取合同列表数据 */
		get_contracts(curr_page, state){
			this.loading = true
			this.axios.get("api/in-sale/contractsByPage",{
				params:{"currPage":curr_page,
					"pageSize":this.page_size,
					"state":state,
					"search":this.search,
					"searchBy":this.searchBy}})
			.then(res => {
				this.contracts = res.data.data
				this.total = res.data.total
				this.loading = false
			})
			.catch(() => {
				this.loading = false
				this.global.mes_error("获取数据失败！")
			})
		},
		/* 获取全部合同数据，用于导出excel */
		get_all_contract(){
			this.axios.get("api/in-sale/contracts")
			.then(res => {
				this.allContract = res.data
			})
			.catch(() => {
				this.global.mes_error("获取数据失败！")
			})
		},
		/* tabs导航改变事件 */
		chang_tab(tab){
			this.state = tab.$attrs.state	// 记录合同状态，在分页时候会用到
			this.get_contracts(this.curr_page, tab.$attrs.state)
		},
		/* 分页页码改变事件 */
		changge_page(curr){
			this.get_contracts(curr, this.state)
		},
		openSave(){
			this.savaContractDialogVisible = !this.savaContractDialogVisible
		},
		//上传文件时处理方法  
        handleChange(file, fileList){
            this.fileTemp = file.raw;
            if(this.fileTemp){
				window.console.log(this.fileTemp.type)
                this.importfxx(this.fileTemp);
            } else {
                this.$message({
                    type:'warning',
                    message:'请上传附件！'
                })
            }
        },
        //超出最大上传文件数量时的处理方法
        handleExceed(){
            this.$message({
                type:'warning',
                message:'超出最大上传文件数量的限制！'
            })
            return;
        },
       /*  //移除文件的操作方法
        handleRemove(file,fileList){
            this.fileTemp = null
		}, */
		// 导入excel
        importfxx(obj) {
            let _this = this;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
 
            var reader = new FileReader();
            FileReader.prototype.readAsBinaryString = function(f) {
                var binary = "";
                var rABS = false; //是否将文件读取为二进制字符串
                var pt = this;
                var wb; //读取完成的数据
                var outdata;
                var reader = new FileReader();
                reader.onload = function(e) {
                    var bytes = new Uint8Array(reader.result);
                    var length = bytes.byteLength;
                    for (var i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //此处引入，用于解析excel
                    var XLSX = require("xlsx");
                    if (rABS) {
                        wb = XLSX.read(btoa(fixdata(binary)), {
                        //手动转化
                        type: "base64"
                        });
                    } else {
                        wb = XLSX.read(binary, {
                        type: "binary"
                        });
                    }
                    outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); 
                    window.console.log(outdata)
					//outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
					let arr = []
					outdata.map(v => {
						let contract = {customer:{},classify:{},empSigner:{}}
						contract.customer.customerName = v["客户"]
						contract.classify.name = v["分类"]
						contract.startTime = [formatTimeToStr(v["开始时间"],"yyyy-MM-dd"), formatTimeToStr(v["结束时间"],"yyyy-MM-dd")]
						contract.customerSigner = v["客户签约人"]
						contract.empSigner.empName = v["我方签约人"]
						contract.signTime = formatTimeToStr(v["签约时间"],"yyyy-MM-dd")
						arr.push(contract)
					})
					_this.tempContracts = arr
					this.fileTemp = null
                };
                reader.readAsArrayBuffer(f);
            };
            if (rABS) {
                reader.readAsArrayBuffer(f);
            } else {
                reader.readAsBinaryString(f);
            }
        }
	},
	created() { 
		this.get_conState()
		/* 初始化结束后保存当前页面对象 */
		this.$store.dispatch("setVueContracte",this)
		this.get_all_contract()
	}

};
</script>

<style scoped>
* {margin: 0;padding: 0;}
.contract_main {background: #e4e7ee;}
.head {height: 70px;background: #f8f6f8;line-height: 70px;}
.contract_title {display: inline-block;font-weight: unset; margin-left: 20px;}
.el-col span {color: #b4b4bc;}
.nav {margin: 20px;background: #fcfbfd;width: 100%-40px;height:auto; min-height:55px !important;line-height: 55px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
.nav .nav-item {display: inline-block;height: 45px;padding: 0px 15px;border-right: 1px solid #dcdfe6;line-height: 45px;}
.content {margin: 20px;background: #fcfbfd;width: 100%-40px;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
#app> section> section> main> div> div.content> div> div.el-tabs__header.is-top { margin: 0 !important;}
.el-button--text {color: #606266;font-size: 14px;}
.el-dropdown-link{color:#606266 !important;}
</style>